package com.fjnu.controller;

import com.fjnu.dao.CategoryDao;
import com.fjnu.dto.ResponseResult;
import com.fjnu.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/blog-api/v0.1/category")
public class CategoryController {

    @Autowired
    private CategoryDao categoryDao;

    /**
     * 删除指定的分类
     */
    @GetMapping("/delete")
    public ResponseResult delete(@RequestParam String categoryId) {
        try {
            Integer id = Integer.parseInt(categoryId);
            int result = categoryDao.delete(id);
            if (result > 0) {
                return ResponseResult.success(null);
            } else {
                return ResponseResult.error("删除分类失败，可能分类不存在或有关联文章");
            }
        } catch (NumberFormatException e) {
            return ResponseResult.error("分类ID格式错误");
        } catch (Exception e) {
            return ResponseResult.error("删除分类异常: " + e.getMessage());
        }
    }

    /**
     * 新增分类
     */
    @PostMapping("/add")
    public ResponseResult add(@RequestBody Category category) {
        try {
            int result = categoryDao.insert(category);
            if (result > 0) {
                return ResponseResult.success(null);
            } else {
                return ResponseResult.error("新增分类失败");
            }
        } catch (Exception e) {
            return ResponseResult.error("新增分类异常: " + e.getMessage());
        }
    }

    /**
     * 罗列分类
     */
    @GetMapping("/list")
    public ResponseResult<List<Category>> list() {
        try {
            List<Category> categories = categoryDao.selectAll();
            return ResponseResult.success(categories);
        } catch (Exception e) {
            return ResponseResult.error("查询分类列表失败: " + e.getMessage());
        }
    }
}